import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Spin, Image, Button} from 'antd';
import styles from './index.less';
import { getResult } from '@/services/api';
import { TransformWrapper, TransformComponent } from 'react-zoom-pan-pinch';
import DownloadComponent from '../../download';
import Outpainting from '../outpainting';
import { ExpandOutlined } from '@ant-design/icons';
import Lottie from 'lottie-react';
import defaultAnimation from '@/assets/json/loading-data.json';


interface PreviewProps {
  taskId: string | null;
  model: string;
  onOutpaintingClick: () => void;
  onTaskGenerated?: (taskId: string, model: string) => void;
}

// 预览组件
const Preview: React.FC<PreviewProps> = ({ taskId, model, onOutpaintingClick, onTaskGenerated }) => {

  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [centerPoint, setCenterPoint] = useState({ x: 0, y: 0 });
  const imageRef = useRef<HTMLImageElement>(null);
  const transformComponentRef = useRef<any>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [selectedIndex, setSelectedIndex] = useState<number>(0);
  const [showOutpainting, setShowOutpainting] = useState(false);
  const [taskImages, setTaskImages] = useState<Map<string, string[]>>(new Map());
  const [error, setError] = useState<string | null>(null);

  // 轮询获取任务结果
  useEffect(() => {
    if (!taskId) return;
    
    setError(null);
    setLoading(true);

    let waitSeconds = 1;           // 初始等待时间：1秒
    const maxWaitSeconds = 5;      // 最大等待时间：5秒
    const incrementSteps = 3;      // 每3次轮询后增加等待时间
    let step = 0;
    let intervalId: NodeJS.Timeout;

    const fetchImageUrls = async () => {
      try {
        console.log('开始获取任务结果，当前 taskId:', taskId, '模型:', model);
        const urls = await getResult(taskId, model);
        
        if (urls === null) {
          console.log('获取结果为null，结束轮询');
          setLoading(false);
          setError('获取结果失败，请重试');
          clearTimeout(intervalId);
          return;
        }

        if (urls.length > 0) {
          setTaskImages(prev => {
            const newMap = new Map(prev);
            if (!newMap.has(taskId)) {
              newMap.set(taskId, urls);
              setImageUrls(prevUrls => {
                const newUrls = [...new Set([...prevUrls, ...urls])];
                const last10Urls = newUrls.slice(-15);
                setSelectedImage(last10Urls[last10Urls.length - 1]);
                setSelectedIndex(last10Urls.length - 1);
                return last10Urls;
              });
            }
            return newMap;
          });
          setLoading(false);
          clearTimeout(intervalId);
        }
      } catch (error) {
        console.error('获取结果失败:', error);
        setLoading(false);
        setError('获取结果失败，请重试');
        clearTimeout(intervalId);
      }
    };

    const poll = () => {
      step += 1;
      console.log(`第 ${step} 次轮询，等待时间: ${waitSeconds}秒`);

      // 达到最大轮询次数
      if (step > 12) {
        console.log('达到最大轮询次数，停止轮询');
        setLoading(false);
        setError('获取结果失败，请重试');
        clearTimeout(intervalId);
        return;
      }

      // 动态调整等待时间
      //每3次轮询后，等待时间翻倍，但不超过最大等待时间5秒
      if (waitSeconds < maxWaitSeconds && step % incrementSteps === 0) {
        waitSeconds = Math.min(waitSeconds * 2, maxWaitSeconds);
      }

      fetchImageUrls();
      
      // 设置下一次轮询
      intervalId = setTimeout(poll, waitSeconds * 1000);
    };

    // 开始轮询
    poll();

    return () => {
      if (intervalId) {
        clearTimeout(intervalId);
      }
    };
  }, [taskId, model]);

  // 预览图片展示和鼠标滚轮缩放
  useEffect(() => {
    if (imageRef.current) {
      const rect = imageRef.current.getBoundingClientRect();
      setCenterPoint({
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2
      });
    }
  }, [selectedImage]);

  const ZOOM_SPEED = 0.2;

  const handleWheel = useCallback((event: WheelEvent) => {
    event.preventDefault();
    
    if (!transformComponentRef.current) return;

    const transformComponent = transformComponentRef.current;
    
    if (event.deltaY < 0) {
      transformComponent.zoomIn(ZOOM_SPEED);
    } else {
      transformComponent.zoomOut(ZOOM_SPEED);
    }
  }, []);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    container.addEventListener('wheel', handleWheel, { passive: false });

    return () => {
      container.removeEventListener('wheel', handleWheel);
    };
  }, [handleWheel]);

  const handleImageClick = (url: string, index: number) => {
    setSelectedImage(url);
    setSelectedIndex(index);
  };

  const handleOutpaintingClick = () => {
    if (selectedImage) {
      setShowOutpainting(true);
    }
  };


  return (
    <div className={styles.preview}>
      <div className={styles.previewHeader}>
        <div className={styles.previewHeaderLeft}>
          <h4 className={styles.previewTitle}>预览</h4>
        </div>
        <div className={styles.previewHeaderCenter}>
          {selectedImage && (
            <Button 
              type="text"
              icon={<ExpandOutlined />}
              onClick={handleOutpaintingClick}
              className={styles.expandButton}
            >
              扩图
            </Button>
          )}
        </div>
        <div className={styles.previewHeaderRight}>
          {selectedImage && <DownloadComponent imageUrl={selectedImage} />}
        </div>
      </div>

      <div 
        ref={containerRef}
        className={styles.previewImg} 
      >
        {loading ? (
          <div className={styles.loadingState}>
            <Spin tip="生成中..." />
          </div>
        ) : selectedImage ? (
          <TransformWrapper
            ref={transformComponentRef}
            initialScale={0.9}
            minScale={0.1}
            maxScale={4}
            wheel={{ disabled: true }}
            centerOnInit={true}
            limitToBounds={true}
            doubleClick={{ disabled: true }}
            centerZoomedOut={true}
            panning={{ disabled: false }}
            pinch={{ disabled: false }}
          >
            <TransformComponent
              wrapperStyle={{
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}
              contentStyle={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '100%',
                height: '100%'
              }}
            >
              <img
                ref={imageRef}
                src={selectedImage}
                alt="Selected"
                style={{ 
                  maxWidth: '100%',
                  maxHeight: '100%',
                  objectFit: 'contain',
                  pointerEvents: 'none',
                  margin: 'auto'
                }}
              />
            </TransformComponent>
          </TransformWrapper>
        ) : (
          <div className={styles.defaultAnimation}>
            <Lottie
              animationData={defaultAnimation}
              loop={true}
              autoplay={true}
              style={{
                width: '100%',
                height: '100%',
                maxWidth: '400px', // 可以调整大小
                maxHeight: '300px',
                opacity: 0.8, // 可以调整透明度
              }}
            />
            <div className={styles.placeholderText}>
              点击「立即生成」开始创作
            </div>
          </div>
        )}
      </div>

      {imageUrls.length > 0 && (
        <div className={styles.previewResult}>
          <div className={styles.resultItemGroup}>
            {imageUrls.map((url, index) => (
              <div 
                key={index} 
                className={`${styles.resultItem} ${selectedIndex === index ? styles.selected : ''}`}
                onClick={() => handleImageClick(url, index)}
              >
                <Image 
                  src={url} 
                  alt={`Result ${index}`} 
                  preview={false}
                  className={styles.resultItemImg}
                />
              </div>
            ))}
          </div>
        </div>
      )}

      {showOutpainting && selectedImage && (
        <div style={{ 
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 1000 
        }}>
          <Outpainting 
            imageUrl={selectedImage} 
            onClose={() => setShowOutpainting(false)}
            onTaskGenerated={onTaskGenerated}
          />
        </div>
      )}
    </div>
  );
}

export default Preview;

